package com.dao.impl;

import java.util.List;

import javax.annotation.Resource;


import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import com.dao.CartltemDao;
import com.dao.OrdersDao;
import com.dao.ProductDao;
import com.entity.Cartltem;
import com.entity.Orders;
import com.entity.Product;
@Repository
public class CartltemImpl implements CartltemDao{

	@Resource
	private SessionFactory sf;
	@Resource
	private OrdersDao od;
	@Resource
	private ProductDao pd;
	@Override
	
	public void addCartltem(int product_id,int orders_id,Cartltem cartltem) {
		Orders orders=od.finOrders(orders_id);
		Product product=pd.finProduct(product_id);
		cartltem.setProduct(product);
		cartltem.setCount(1);
		cartltem.setOrders(orders);
		cartltem.setPrice(product.getDiscountprice());
		cartltem.setState(0);
		this.sf.getCurrentSession().save(cartltem);
		orders.setPrice(orders.getPrice()+cartltem.getPrice());
		this.sf.getCurrentSession().update(orders);
	}

	@Override
	public void deleteCartltem(int id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Cartltem finCart(int product_id, int orders_id) {
		//某个di
		String hql="from Cartltem where pid=? and oid=?";
		Query query=this.sf.getCurrentSession().createQuery(hql);
		query.setParameter(0, product_id);
		query.setParameter(1, orders_id);
		Cartltem cart=(Cartltem)query.uniqueResult();
		return cart;
	}

	@Override
	public void pushOneCart(int orders_id,Cartltem cart) {
		//购物项数量加一，同时订单的价格也需要变
		Orders orders=od.finOrders(orders_id);
		cart.setCount(cart.getCount()+1);
		cart.setPrice(cart.getProduct().getDiscountprice()*cart.getCount());
		this.sf.getCurrentSession().update(cart);
		orders.setPrice(orders.getPrice()+(cart.getPrice()/cart.getCount()));
		this.sf.getCurrentSession().update(orders);
		
	}

	@Override
	public List<Cartltem> finall(int orders_id) {
		//找到属于某个订单并且购物项的状态是0的购物项
		String hql="from Cartltem where oid=? and state=0";
		Query query=this.sf.getCurrentSession().createQuery(hql);
		query.setParameter(0, orders_id);
		List<Cartltem> list=query.list();
		return list;
	}

	@Override
	public void updateCart(List<Cartltem> carts) {
		//订单提交后，属于这个订单的购物项状态全部设置为1
		for(Cartltem cart:carts){
			cart.setState(1);
			this.sf.getCurrentSession().update(cart);
		}
		
	}

	@Override
	public void subOneCart(int orders_id, Cartltem cart) {
		//购物项数量减一，同时订单的价格也需要变
		Orders orders=od.finOrders(orders_id);
		cart.setCount(cart.getCount()-1);
		cart.setPrice(cart.getProduct().getDiscountprice()*cart.getCount());
		this.sf.getCurrentSession().update(cart);
		orders.setPrice(orders.getPrice()-(cart.getPrice()/cart.getCount()));
		this.sf.getCurrentSession().update(orders);
		
	}

}
